/**
 * 研发流程状态机实现
 * 基于《研发流程设计指引》和《状态机》文档
 */

// 引入依赖
const { observable, action, computed } = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getNpmPath('mobx-miniprogram(_, __, pkg, file) => file ? '/' + file : ''');
const cloudHelper = require('./helpers/cloud_helper.js');
const timeHelper = require('./helpers/time_helper.js');
const pageHelper = require('./helpers/page_helper.js');

/**
 * 项目状态定义
 */
const PROJECT_STATUS = {
  PROJECT_REVIEW: 1,  // 项目审核
  DORMANT: 2,         // 休眠
  ACTIVE: 3,          // 活动
  COMPLETED: 99       // 已完成
};

/**
 * 活动状态定义
 */
const ACTIVE_STATE = {
  HARDWARE_CONFIRM: 'hardware_confirm',         // 硬件确认
  HARDWARE: 'hardware',                         // 硬件
  DEBUG: 'debug',                               // 调试
  DATA_SYNC: 'data_sync',                       // 资料同步
  TESTING: 'testing',                           // 测试
  CUSTOMER_CONFIRM: 'customer_confirm',         // 客户确认
  ORDER_PREPARATION: 'order_preparation',       // 订单准备 
  PRODUCTION: 'production',                     // 生产
  PRODUCT_FEEDBACK: 'product_feedback'          // 待反馈
};

/**
 * 子状态定义
 */
const SUB_STATE = {
  // 项目审核子状态
  DIRECTOR: 'director',           // 董事长
  RD_MANAGER: 'rd_manager',       // 研发经理
  ASSIGNMENT: 'assignment',       // 分配
  
  // 休眠子状态
  REVIEW: 'review',               // 审核
  ARCHIVE: 'archive',             // 归档
  
  // 硬件子状态
  DESIGN: 'design',               // 设计
  REVIEW: 'review',               // 审核
  SAMPLE: 'sample',               // 打样
  PRODUCTION_SAMPLE: 'prod_sample', // 制样
  IN_STOCK: 'in_stock',           // 在库
  
  // 测试子状态
  TESTING: 'testing',             // 测试中
  NO_TEST_REVIEW: 'no_test_review', // 免测审核
  
  // 客户确认子状态
  DELIVERY: 'delivery',           // 寄样
  TESTING: 'testing',             // 测试
  NO_SAMPLE_REVIEW: 'no_sample_review', // 无签样审核
  SAMPLE_IN_STOCK: 'sample_in_stock',   // 样品在库
  ARCHIVE: 'archive',             // 归档
  
  // 订单准备子状态
  WAITING: 'waiting',             // 待量产
  REVIEW: 'review',               // 审核
  DOC_CONTROL: 'doc_control',     // 文控
  SUPPLEMENT: 'supplement',       // 补充资料
  PRE_MEETING: 'pre_meeting',     // 产前会
  PREPARATION: 'preparation',     // 生产准备
  
  // 生产子状态
  PRODUCING: 'producing',         // 生产中
  PE_HANDLING: 'pe_handling',     // PE处理
  RD_CHECKING: 'rd_checking',     // 研发排查
  COMPLETED: 'completed'          // 完成
};

/**
 * 状态事件定义
 */
const STATE_EVENTS = {
  // 项目审核事件
  SUBMIT_REQUEST: 'submit_request',              // 提交功能需求表
  DIRECTOR_APPROVE: 'director_approve',          // 董事长审核通过
  DIRECTOR_REJECT: 'director_reject',            // 董事长审核不通过
  MANAGER_APPROVE: 'manager_approve',            // 研发经理审核通过
  MANAGER_REJECT: 'manager_reject',              // 研发经理审核不通过
  PROJECT_ASSIGN_COMPLETE: 'project_assign_complete', // 提交分配
  
  // 休眠事件
  SLEEP_REQUEST: 'sleep_request',                // 业务提交休眠申请
  SLEEP_APPROVE: 'sleep_approve',                // 休眠审核通过
  SLEEP_REJECT: 'sleep_reject',                  // 休眠审核不通过
  WAKEUP_REQUEST: 'wakeup_request',              // 业务提交唤醒申请
  
  // 硬件确认事件
  HW_CONFIRM_COMPLETED: 'hw_confirm_completed',  // 硬件确认完成
  HW_EXISTING: 'hw_existing',                    // 已有硬件
  
  // 硬件设计打样事件
  HW_DESIGN_SUBMIT: 'hw_design_submit',          // 提交硬件设计审核
  HW_DESIGN_REVIEW_PASS: 'hw_design_review_pass', // 硬件审核通过
  HW_DESIGN_REVIEW_FAIL: 'hw_design_review_fail', // 硬件审核不通过
  PURCHASE_COMPLETE: 'purchase_complete',        // 采购完成
  PURCHASE_ISSUE: 'purchase_issue',              // 采购物料异常
  SAMPLE_MAKING_COMPLETE: 'sample_making_complete', // 样品制作完成
  
  // 更多事件...
};

/**
 * 状态与角色权限映射
 */
const STATUS_ROLE_PERMISSIONS = {
  // 项目审核状态权限
  [PROJECT_STATUS.PROJECT_REVIEW]: {
    [SUB_STATE.DIRECTOR]: ['director'], // 待董事长审核：董事长
    [SUB_STATE.RD_MANAGER]: ['research_manager'], // 待研发经理审核：研发经理
    [SUB_STATE.ASSIGNMENT]: ['research_manager'], // 项目分配：研发经理
  },
  
  // 休眠状态权限
  [PROJECT_STATUS.DORMANT]: {
    [SUB_STATE.REVIEW]: ['research_manager'], // 研发审核：研发经理
    [SUB_STATE.ARCHIVE]: ['document_controller'], // 休眠归档：文控
  },
  
  // 活动状态权限
  [PROJECT_STATUS.ACTIVE]: {
    [ACTIVE_STATE.HARDWARE_CONFIRM]: ['hardware_engineer'], // 硬件确认：硬件工程师
    [ACTIVE_STATE.HARDWARE]: ['hardware_engineer', 'research_manager', 'purchaser', 'sample_team'], // 硬件
    [ACTIVE_STATE.DEBUG]: ['software_engineer'], // 调试：软件工程师
    [ACTIVE_STATE.DATA_SYNC]: ['software_engineer'], // 资料同步：软件工程师指定人员
    [ACTIVE_STATE.TESTING]: ['tester', 'research_manager'], // 测试：测试组人员
    [ACTIVE_STATE.CUSTOMER_CONFIRM]: ['receptionist', 'business_staff', 'director', 'sample_manager', 'document_controller'], // 客户确认
    [ACTIVE_STATE.ORDER_PREPARATION]: ['business_staff', 'director', 'document_controller', 'secretary'], // 订单准备
    [ACTIVE_STATE.PRODUCTION]: ['production_supervisor', 'production_engineer', 'software_engineer'], // 生产
    [ACTIVE_STATE.PRODUCT_FEEDBACK]: ['business_staff', 'director'] // 待反馈：业务人员
  }
};

/**
 * 状态转换规则定义
 */
const STATE_TRANSITIONS = {
  // 项目审核状态转移
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.DIRECTOR_APPROVE}`]: {
    target: PROJECT_STATUS.PROJECT_REVIEW,
    subState: SUB_STATE.RD_MANAGER,
    description: "董事长审核通过",
    roles: ["director"]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.DIRECTOR_REJECT}`]: {
    target: PROJECT_STATUS.DORMANT,
    subState: SUB_STATE.ARCHIVE,
    description: "项目立项不通过",
    roles: ["director"]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.MANAGER_APPROVE}`]: {
    target: PROJECT_STATUS.PROJECT_REVIEW,
    subState: SUB_STATE.ASSIGNMENT,
    description: "研发经理审核通过",
    roles: ["research_manager"]
  },
  
  [`${PROJECT_STATUS.PROJECT_REVIEW}_${STATE_EVENTS.PROJECT_ASSIGN_COMPLETE}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.HARDWARE_CONFIRM,
    description: "提交分配",
    roles: ["research_manager"]
  },
  
  // 休眠状态转移
  [`${PROJECT_STATUS.ACTIVE}_${STATE_EVENTS.SLEEP_REQUEST}`]: {
    target: PROJECT_STATUS.DORMANT,
    subState: SUB_STATE.REVIEW,
    description: "业务提交休眠申请",
    roles: ["business_staff"]
  },
  
  [`${PROJECT_STATUS.DORMANT}_${STATE_EVENTS.SLEEP_APPROVE}`]: {
    target: PROJECT_STATUS.DORMANT,
    subState: SUB_STATE.ARCHIVE,
    description: "审核通过",
    roles: ["research_manager"]
  },
  
  // 硬件确认状态转移
  [`${ACTIVE_STATE.HARDWARE_CONFIRM}_${STATE_EVENTS.HW_CONFIRM_COMPLETED}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.HARDWARE,
    subState: SUB_STATE.DESIGN,
    description: "无现成硬件/硬件变更",
    roles: ["hardware_engineer"]
  },
  
  [`${ACTIVE_STATE.HARDWARE_CONFIRM}_${STATE_EVENTS.HW_EXISTING}`]: {
    target: PROJECT_STATUS.ACTIVE,
    activeState: ACTIVE_STATE.DEBUG,
    description: "已有硬件/软件变更",
    roles: ["hardware_engineer"]
  },
  
  // 更多转换规则...
};

/**
 * 研发流程状态机Store
 */
const researchStateMachineStore = observable({
  // 当前项目数据
  project: null,
  
  // 当前用户角色
  currentRole: '',
  
  // 当前状态下可用的事件
  availableEvents: [],
  
  // 流程历史记录
  flowHistory: [],
  
  // 加载状态
  loading: {
    project: false,
    events: false,
    flowHistory: false
  },
  
  // 错误状态
  error: {
    project: null,
    events: null,
    flowHistory: null
  },
  
  // 设置项目数据
  setProject: action(function(project) {
    if (!project) return;
    
    this.project = project;
    
    // 重置错误
    this.error.project = null;
    
    // 加载该项目状态下可用的事件
    this.loadAvailableEvents();
  }),
  
  // 设置当前角色
  setCurrentRole: action(function(role) {
    this.currentRole = role;
    
    // 更新可用事件
    this.loadAvailableEvents();
  }),
  
  // 获取可用的事件列表
  getAvailableEvents: function() {
    // 如果项目未加载，返回空数组
    if (!this.project) {
      return [];
    }
    
    // 获取当前状态
    const currentStatus = this.project.RESEARCH_STATUS || 0;
    const currentActiveState = this.project.RESEARCH_ACTIVE_STATE || '';
    const currentSubStatus = this.project.RESEARCH_SUB_STATUS || '';
    
    try {
      // 获取可用事件
      const events = [];
      
      // 遍历所有转换规则
      Object.entries(STATE_TRANSITIONS).forEach(([key, transition]) => {
        // 解析key中的状态和事件
        const [stateStr, eventId] = key.split('_');
        
        // 检查状态匹配
        let stateMatch = false;
        
        // 匹配主状态
        if (stateStr == currentStatus) {
          stateMatch = true;
        }
        // 匹配活动状态
        else if (stateStr === currentActiveState) {
          stateMatch = true;
        }
        
        // 如果状态匹配且角色有权限，添加到可用事件列表
        if (stateMatch && transition.roles && transition.roles.includes(this.currentRole)) {
          events.push({
            id: eventId,
            name: transition.description,
            target: transition.target,
            activeState: transition.activeState,
            subState: transition.subState
          });
        }
      });
      
      return events;
    } catch (error) {
      console.error('获取可用事件失败:', error);
      return [];
    }
  },
  
  // 加载可用事件
  loadAvailableEvents: action(function() {
    try {
      this.loading.events = true;
      
      // 获取可用事件
      this.availableEvents = this.getAvailableEvents();
      
      this.loading.events = false;
      this.error.events = null;
    } catch (error) {
      console.error('加载可用事件失败:', error);
      this.loading.events = false;
      this.error.events = error.message || '加载可用事件失败';
      this.availableEvents = [];
    }
  }),
  
  // 加载流程历史
  loadFlowHistory: action(async function(projectId) {
    if (!projectId) return [];
    
    try {
      this.loading.flowHistory = true;
      
      // 请求服务器获取流程历史
      const params = { projectId };
      const result = await cloudHelper.callCloudData('research/get_flow_history', params);
      
      // 处理时间显示
      if (result && Array.isArray(result)) {
        result.forEach(item => {
          if (item && item.FLOW_TIME) {
            item.FLOW_TIME_DISPLAY = timeHelper.formatDateTime(item.FLOW_TIME);
          }
        });
        
        // 更新Store中的流程历史
        this.flowHistory = result;
      } else {
        this.flowHistory = [];
      }
      
      this.loading.flowHistory = false;
      this.error.flowHistory = null;
      
      return this.flowHistory;
    } catch (error) {
      console.error('加载流程历史失败:', error);
      this.loading.flowHistory = false;
      this.error.flowHistory = error.message || '加载流程历史失败';
      this.flowHistory = [];
      return [];
    }
  }),
  
  // 提交状态转换
  performStateTransition: action(async function(params) {
    if (!params || !params.projectId || !params.eventId) {
      throw new Error('状态转换参数不完整');
    }
    
    try {
      // 获取转换定义
      const currentStatus = this.project.RESEARCH_STATUS || 0;
      const currentActiveState = this.project.RESEARCH_ACTIVE_STATE || '';
      const eventId = params.eventId;
      
      // 尝试匹配活动状态的转换
      let transition = null;
      if (currentActiveState) {
        const activeStateKey = `${currentActiveState}_${eventId}`;
        transition = STATE_TRANSITIONS[activeStateKey];
      }
      
      // 如果没有找到活动状态的转换，尝试匹配主状态的转换
      if (!transition) {
        const mainStateKey = `${currentStatus}_${eventId}`;
        transition = STATE_TRANSITIONS[mainStateKey];
      }
      
      if (!transition) {
        throw new Error(`找不到状态转换: ${currentStatus}_${eventId} 或 ${currentActiveState}_${eventId}`);
      }
      
      // 准备转换数据
      const transitionData = {
        ...params,
        target: transition.target,
        activeState: transition.activeState,
        subState: transition.subState,
        description: transition.description
      };
      
      // 请求服务器执行状态转换
      const result = await cloudHelper.callCloudData('research/perform_state_transition', transitionData);
      
      // 更新项目状态
      if (result && result.project) {
        this.setProject(result.project);
      }
      
      // 重新加载流程历史
      if (params.projectId) {
        this.loadFlowHistory(params.projectId);
      }
      
      return result;
    } catch (error) {
      console.error('提交状态转换失败:', error);
      throw error;
    }
  }),
  
  // 获取状态名称
  getStatusName: function(status) {
    const statusNames = {
      [PROJECT_STATUS.PROJECT_REVIEW]: '项目审核',
      [PROJECT_STATUS.DORMANT]: '休眠',
      [PROJECT_STATUS.ACTIVE]: '活动',
      [PROJECT_STATUS.COMPLETED]: '已完成'
    };
    
    return statusNames[status] || '未知状态';
  },
  
  // 获取活动状态名称
  getActiveStateName: function(activeState) {
    const activeStateNames = {
      [ACTIVE_STATE.HARDWARE_CONFIRM]: '硬件确认',
      [ACTIVE_STATE.HARDWARE]: '硬件',
      [ACTIVE_STATE.DEBUG]: '调试',
      [ACTIVE_STATE.DATA_SYNC]: '资料同步',
      [ACTIVE_STATE.TESTING]: '测试',
      [ACTIVE_STATE.CUSTOMER_CONFIRM]: '客户确认',
      [ACTIVE_STATE.ORDER_PREPARATION]: '订单准备', 
      [ACTIVE_STATE.PRODUCTION]: '生产',
      [ACTIVE_STATE.PRODUCT_FEEDBACK]: '待反馈'
    };
    
    return activeStateNames[activeState] || activeState;
  },
  
  // 获取事件名称
  getEventName: function(eventId) {
    // 从转换规则中查找事件描述
    for (const [key, transition] of Object.entries(STATE_TRANSITIONS)) {
      if (key.endsWith(`_${eventId}`)) {
        return transition.description;
      }
    }
    
    return eventId;
  }
});

// 导出状态机常量和store
module.exports = {
  PROJECT_STATUS,
  ACTIVE_STATE,
  SUB_STATE,
  STATE_EVENTS,
  STATUS_ROLE_PERMISSIONS,
  STATE_TRANSITIONS,
  researchStateMachineStore
}; 